package by.koleda.photoupdater.service;

import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import by.koleda.photoupdater.helpers.ParamCallback;
import by.koleda.photoupdater.manager.ContactsManager;
import by.koleda.photoupdater.manager.ContentManager;
import by.koleda.photoupdater.model.VkProfile;

public class HttpService extends Service implements ParamCallback<List<VkProfile>> {

	public static final String EXTRA_KEY_MESSAGE = "message";

	public static final String ACTION_ON_ERROR = "by.koleda.photoupdater.service.HTTP_SERVICE_ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.koleda.photoupdater.service.HTTP_SERVICE_ACTION_ON_SUCCESS";
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	    handleCommand(intent);
	    return START_STICKY;
	}

	protected void handleCommand(Intent intent) {
		if (intent == null) {
			return;
		}
		ContentManager.getInstance().getContent(HttpService.this, this);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onSuccess(final List<VkProfile> p) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ContactsManager.addNewVkProfiles(getApplicationContext(), p);
				Intent intent = new Intent(ACTION_ON_SUCCESS);
				sendBroadcast(intent);
			}	
		}).start();
	}

	@Override
	public void onError(Throwable e) {
		Intent intent = new Intent(ACTION_ON_ERROR);
		intent.putExtra(EXTRA_KEY_MESSAGE, e.getMessage());
		sendBroadcast(intent);
	}
}